package com.tdk.wifidirectserver.util

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.wifi.WifiManager
import android.net.wifi.p2p.WifiP2pConfig
import android.net.wifi.p2p.WifiP2pDevice
import android.net.wifi.p2p.WifiP2pManager
import android.os.Build
import android.os.Looper.getMainLooper
import android.util.Log
import com.tdk.wifidirectserver.MyApplication
import com.tdk.wifidirectserver.inter.WifiDirectActionListener
import com.tdk.wifidirectserver.receiver.DirectBroadcastReceiver


val mConnectivityUtil: ConnectivityUtil by lazy {
    ConnectivityUtil.getInstance(MyApplication.instance!!)
}

@SuppressLint("MissingPermission")
class ConnectivityUtil private constructor(private val context: Context) {
    private val TAG: String = ConnectivityUtil::class.java.simpleName
    private val connectivityManager: ConnectivityManager? by lazy {
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    }

    private val network: Network? = connectivityManager?.activeNetwork
    val capabilities: NetworkCapabilities? by lazy {
        if (connectivityManager == null || network == null) {
            Log.e(TAG, "connectivityManager:$connectivityManager or network :$network is null")
            null
        }else{
            connectivityManager!!.getNetworkCapabilities(network!!)
        }
    }

    private val wifiManager: WifiManager by lazy {
        context.getSystemService(Context.WIFI_SERVICE) as WifiManager
    }
    private var mWifiP2pManager: WifiP2pManager? = null
    private var mChannel: WifiP2pManager.Channel? = null
    private val mWifiP2pDevice: WifiP2pDevice? = null
    private var broadcastReceiver: BroadcastReceiver? = null
    private val mWifiP2pEnabled = false
    private var mWifiP2pDeviceList: List<WifiP2pDevice>? = null
    private val mChannelListener: WifiP2pManager.ChannelListener by lazy {
        WifiP2pManager.ChannelListener {
            Log.d(TAG, "onChannelDisconnected: ")
            if (mActionListener == null) {
                Log.d(TAG, ":   mActionListener is null")
                return@ChannelListener
            }
            mActionListener!!.onChannelDisconnected()
        }
    }
    private var mActionListener: WifiDirectActionListener? = null

    fun initConfig(
        mWifiDirectActionListener: WifiDirectActionListener
    ) {
        Log.d(TAG, " ConnectivityUtil initConfig")
        mWifiP2pManager = context.getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager?
        mChannel = mWifiP2pManager!!.initialize(context, getMainLooper(), mChannelListener)
        broadcastReceiver = DirectBroadcastReceiver(mWifiP2pManager!!, mChannel!!, mWifiDirectActionListener)
        context.registerReceiver(broadcastReceiver, DirectBroadcastReceiver.intentFilter)
        //如果需要P2P设备列表的话，可以在这里初始化一个集合
        mWifiP2pDeviceList = ArrayList()
    }

    fun unRegisterBroadcastReceiver() {
        if (broadcastReceiver != null) {
            context.unregisterReceiver(broadcastReceiver)
        }
    }

    companion object : SingleArgSingletonHolder<ConnectivityUtil, Context>(::ConnectivityUtil)

    @SuppressLint("MissingPermission")
    fun discoverPeers(listener: WifiP2pManager.ActionListener) {
        if (mWifiP2pManager == null) {
            Log.e(TAG, "discoverPeers: mWifiP2pManager is null")
            return
        }
        mWifiP2pManager!!.discoverPeers(mChannel, listener)
    }

    //停止搜索
    fun stopPeerDiscovery(listener: WifiP2pManager.ActionListener) {
        if (mWifiP2pManager == null) {
            Log.e(TAG, "stopPeerDiscovery: mWifiP2pManager is null")
            return
        }
        mWifiP2pManager!!.stopPeerDiscovery(mChannel, listener)
    }


    //连接设备

    @SuppressLint("MissingPermission")
    fun connect(device: WifiP2pDevice, listener: WifiP2pManager.ActionListener) {
        if (mWifiP2pManager == null) {
            Log.e(TAG, "connect: mWifiP2pManager is null")
            return
        }
        val config = WifiP2pConfig()
        config.deviceAddress = device.deviceAddress
        mWifiP2pManager!!.connect(mChannel, config, listener)
    }


    //通过WifiP2pConfig 建立连接
    fun connectWithConfig(config: WifiP2pConfig, listener: WifiP2pManager.ActionListener) {
        if (mWifiP2pManager == null) {
            Log.e(TAG, "connectWithConfig: mWifiP2pManager is null")
            return
        }
        mWifiP2pManager!!.connect(mChannel, config, listener)
    }


    //断开连接
    fun disconnect(listener: WifiP2pManager.ActionListener) {
        if (mWifiP2pManager == null) {
            Log.e(TAG, "disconnect: mWifiP2pManager is null")
            return
        }
        mWifiP2pManager!!.removeGroup(mChannel, listener)
    }


    //取消连接
    fun cancelConnect(listener: WifiP2pManager.ActionListener) {
        if (mWifiP2pManager == null) {
            Log.e(TAG, "cancelConnect: mWifiP2pManager is null")
            return
        }
        mWifiP2pManager!!.cancelConnect(mChannel, listener)
    }

    //创建群组

    fun createGroup(config: WifiP2pConfig?, listener: WifiP2pManager.ActionListener) {
        if (mWifiP2pManager == null) {
            Log.e(TAG, "createGroup: mWifiP2pManager is null")
            return
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && config != null) {
            mChannel?.let { mWifiP2pManager!!.createGroup(it, config, listener) }
        } else {
            mWifiP2pManager!!.createGroup(mChannel, listener)
        }
    }

    fun requestGroupInfo(listener: WifiP2pManager.GroupInfoListener) {
        if (mWifiP2pManager == null) {
            Log.e(TAG, "requestGroupInfo: mWifiP2pManager is null")
            return
        }
        mWifiP2pManager!!.requestGroupInfo(mChannel, listener)
    }


//    WifiP2pManager manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
//    WifiP2pManager.Channel channel = manager.initialize(this, getMainLooper(), null);

//    WifiP2pManager.ActionListener createGroupActionListener = new WifiP2pManager.ActionListener() {
//        @Override
//        public void onSuccess() {
//            // Group creation successful, now request group info
//            manager.requestGroupInfo(channel, new WifiP2pManager.GroupInfoListener() {
//                @Override
//                public void onGroupInfoAvailable(WifiP2pGroup group) {
//                    if (group != null) {
//                        // in group.getNetworkName() you get SSID
//                        // in group.getPassphrase() you get Password
//                        Log.d("WifiP2P", "Group SSID: " + group.getNetworkName());
//                        Log.d("WifiP2P", "Group Passphrase: " + group.getPassphrase());
//                    }
//                }
//            });
//        }
//
//        @Override
//        public void onFailure(int reason) {
//            // Failed to create group
//            Log.d("WifiP2P", "Failed to create group: " + reason);
//        }
//    };
//
//    manager.createGroup(channel, createGroupActionListener);


    //机器是否支持wifi direct
    fun isEnableWifiDirect(): Boolean {
        return wifiManager.isP2pSupported
    }

    fun isOpenWifi(): Boolean {
        return wifiManager.isWifiEnabled
    }

    fun openWifi() {
        wifiManager.isWifiEnabled = true
    }


}